package com.qeegoo.b2bautozityp.moudle.good.view.carmodel;

import android.os.Handler;
import android.view.View;

import com.qeegoo.b2bautozityp.R;
import com.qeegoo.b2bautozityp.databinding.FragGoodsCarmodelAddBinding;
import com.qeegoo.b2bautozityp.injector.component.DaggerGoodsFragmentComponent;
import com.qeegoo.b2bautozityp.moudle.base.BaseFragment;
import com.qeegoo.b2bautozityp.moudle.good.viewmodel.carmodel.CarModelAddViewModel;
import com.qeegoo.b2bautozityp.rxbus.event.CommonEvent;

import javax.inject.Inject;

/**
 * 王少岩 在 2017/9/22 创建了它
 */

public class CarModelAddFragment extends BaseFragment<FragGoodsCarmodelAddBinding> {
    @Inject
    CarModelAddViewModel mViewModel;
    private Handler handler;
    private OverlayThread overlayThread;

    @Override
    protected int attachLayoutRes() {
        return R.layout.frag_goods_carmodel_add;
    }

    @Override
    protected void initInjector() {
        DaggerGoodsFragmentComponent.builder().appComponent(getAppComponent()).fragmentComponent(getFragmentComponent()).build().inject(this);
    }

    @Override
    protected void initViews() {
        handler = new Handler();
        overlayThread = new OverlayThread();
        mBinding.setViewModel(mViewModel);
        mBinding.lvCarmodel.setAdapter(mViewModel.getWrapperAdapter());
        setListener();
    }

    private void setListener() {
        mBinding.indexBarView.setOnTouchLetterChangeListenner((isTouched, s, index) -> {
            int position = 0;
            for (int i = 0; i < index; i++) {
                position += mViewModel.getWrapperAdapter().getChildrenCount(i) + 1;
            }
            mBinding.lvCarmodel.setSelection(position);

            mBinding.tvChar.setText(s);
            mBinding.tvChar.setVisibility(View.VISIBLE);
            handler.removeCallbacks(overlayThread);
            // 延迟一秒后执行，让overlay为不可见
            handler.postDelayed(overlayThread, 1500);
        });

        mViewModel.registerRxBus(CommonEvent.class, commonEvent -> {
            switch (commonEvent.eventType) {
                case CommonEvent.FLAG_COMPLETE:
                    mBinding.indexBarView.setLetters(mViewModel.getLetters());
                    mBinding.indexBarView.setVisibility(View.VISIBLE);
                    for (int i = 0; i < mViewModel.getWrapperAdapter().getGroupCount(); i++) {
                        mBinding.lvCarmodel.expandGroup(i);
                    }
                    break;
            }
        });
    }

    /**
     * 设置overlay不可见
     */
    private class OverlayThread implements Runnable {

        public void run() {
            mBinding.tvChar.setVisibility(View.GONE);
        }

    }
}
